<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/2/5 0005
 * Time: 上午 10:22
 */

namespace app\admin\model;

use think\Model;
use think\Loader;
use think\Validate;
use think\Db;
class Place extends Model
{
    protected  $pk='place_id';//主键
    protected $table = 'xcx_product_place';
    public function add_place($data)
    {
        //halt($data);
        $validate = Loader::validate('Place');

        if (!$validate->check($data)) {
            return ['valid' => 0, 'msg' => $validate->getError()];
        }

        $arr['createtime']=time();
        $arr['place_states']=1;
        $arr['place_name']=$data['place_name'];
        $arr['addr_detail']=$data['addr_detail'];
        $arr['mobile']=$data['mobile'];
        $arr['code']=$data['code'];
        $arr['product_id']=$data['product_id'];
        $p=explode('/',$data['addr_p']);
        $c=explode('/',$data['addr_c']);
        $d=explode('/',$data['addr_d']);
        $arr['place_addr']=$p[1].$c[1].$d[1];
        $arr['addr_id']=$p[0].','.$c[0].','.$d[0];
        //判断商品id名称是否唯一
        $name_yan = $this->where('product_id', $data['product_id'])->find();
       if($data['place_id'])
        {
            if ($name_yan['place_id'] != $data['place_id']) {
                return ['valid' => 0, 'msg' => '输入信息有误,修改失败'];
                exit;
            }
            $result = $this->save($arr,['place_id'=>$data['place_id']]);
        }else
            {
                if ($name_yan['place_id'] != "") {
                    return ['valid' => 0, 'msg' => '该商品发货地址已添加'];
                    exit;
                }
                $result = $this->save($arr);
            }
        if(false == $result){
            // 验证失败 输出错误信息
            return ['valid'=>1,'msg'=>'添加失败'];
        }else{
            return ['valid'=>4,'msg'=>'添加成功'];
        }
    }
    public function getAllPlace($state)
    {
        $res=Db::table('xcx_product_place')
            ->alias('a')
            ->join('products p','a.product_id=p.products_id')
            //->where('place_states',$state)
            ->field('a.place_id,a.place_states,a.place_addr,a.mobile,a.place_name,a.addr_detail,a.createtime,p.products_name,a.code,a.product_id,p.products_id')
           ->order('place_id desc')
            ->select();
        return $res;
    }
    public function getIdPlace($id)
    {
        $res=$this->where('place_id',$id)->find();
        $place=explode(',',$res['addr_id']);
        $res['p']=$place[0];
        $res['c']=$place[1];
        $res['d']=$place[2];
        return $res;
    }
}